import { useQueries } from '@tanstack/react-query';
import WorkOrderServices from '@/api/services/workOrderServices.ts';
import { Result } from '#/api.ts';
import { ReporterInfo } from '#/entity.ts';
import { useCatch } from '@/hooks/useCatch.tsx';
import { useUserId } from '@/store/userStore.ts';
import { useEffect, useState } from 'react';

export type RoleType = 'header' | 'manager' | 'tech' | 'none';

export const useUserRole = () => {
  const [userRole, setUserRole] = useState<RoleType>('none');
  const userId = useUserId();
  const catchFn = useCatch();
  const [{ data: headerList }, { data: userHeaderList }, { data: technicianList }] = useQueries({
    queries: [
      {
        queryKey: ['headerList'],
        queryFn: () => catchFn(() => WorkOrderServices.getHeaderList()),
        select: ({ data }: Result<ReporterInfo[]>) =>
          data.map((item) => ({
            name: item.name,
            id: item.id,
          })),
      },
      {
        queryKey: ['userHeaderList'],
        queryFn: () => catchFn(() => WorkOrderServices.getUserHeaderList()),
        select: ({ data }: Result<ReporterInfo[]>) =>
          data.map((item) => ({
            name: item.name,
            id: item.id,
          })),
      },
      {
        queryKey: ['technicianList'],
        queryFn: () => catchFn(() => WorkOrderServices.getTechnicianList()),
        select: ({ data }: Result<ReporterInfo[]>) =>
          data.map((item) => ({
            name: item.name,
            id: item.id,
          })),
      },
    ],
  });

  useEffect(() => {
    if (headerList?.some((item) => item.id === userId)) {
      setUserRole('header');
    } else if (userHeaderList?.some((item) => item.id === userId)) {
      setUserRole('manager');
    } else if (technicianList?.some((item) => item.id === userId)) {
      setUserRole('tech');
    }
  }, [headerList, userHeaderList, technicianList, userId]);

  return userRole;
};
